package com.module.overview.ui.historicalData

import android.view.View
import androidx.core.content.ContextCompat
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.helper.RouterHelper
import com.common.app.utls.HeadTitleUtils
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.setOnClickListener
import com.common.base.utils.JsonUtils
import com.common.base.utils.LogUtils
import com.common.base.utils.StatusBarUtils
import com.module.ble.data.bean.SleepChartValueData
import com.module.ble.db.table.UserHeartRate
import com.module.ble.db.table.UserSleepInfo
import com.module.overview.R
import com.module.overview.databinding.OverviewActivityHistoricalDataMainBinding
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/07/22
 * <p>
 * 描述：历史数据主页面
 * <p>
 * 修订历史：
 */
class HistoricalDataMainActivity :
    AppActivity<OverviewActivityHistoricalDataMainBinding, HistoricalDataMainViewModel>(),
    View.OnClickListener {

    val TAG: String = HistoricalDataMainActivity::class.java.simpleName

    override fun getViewModel() = HistoricalDataMainViewModel::class.java

    override fun getViewContentBinding() =
        OverviewActivityHistoricalDataMainBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true


    var totalDuration = 0//睡眠总时长，单位：分钟

    var awakeDuration = 0//清醒时长，单位：分钟
    var lightDuration = 0//浅睡时长，单位：分钟
    var remDuration = 0//快速眼动时长，单位：分钟
    var deepDuration = 0//深睡时长，单位：分钟


    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle(getString(R.string.overview_historical_data_hint))
        headTitleUtils.setLineStyle(10)

        //上下拉刷新
        mViewContentBinding.pdView.setEnableLoadMore(false)
        mViewContentBinding.pdView.setEnableLoadMoreWhenContentNotFull(false)
        getRefreshFooter()?.let { mViewContentBinding.pdView.setRefreshFooter(it) }
        mViewContentBinding.pdView.setRefreshHeader(
            ClassicsHeader(this).setAccentColor(
                ContextCompat.getColor(this, R.color.color_999999)
            )
        )

    }

    override fun initEvents() {
        super.initEvents()

        mViewContentBinding.pdView.setRefreshFooter(
            ClassicsFooter(this).setAccentColor(
                ContextCompat.getColor(this, R.color.color_999999)
            )
        )

        mViewContentBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                mViewModel.getTheDayData()
                refreshLayout.layout.postDelayed({
                    finishPdView()
                }, 1000)
            }
        })

        mViewContentBinding.totalSleepBg.setOnClickListener(onClick = this)
        mViewContentBinding.totalAcBg.setOnClickListener(onClick = this)
        mViewContentBinding.totalPressureBg.setOnClickListener(onClick = this)
        mViewContentBinding.totalSignsBg.setOnClickListener(onClick = this)

        mViewModel.curSleepData.observe(this) { sleepDataIt ->
            val listTemp: MutableList<SleepChartValueData> = ArrayList()
            val tempData: List<UserSleepInfo> = sleepDataIt.sortedBy { it.createdTime }//按时间排序（升序）
            LogUtils.d("SleepFragment", "YQ: allSleepData ${JsonUtils.toJson(tempData)}")
            totalDuration = 0
            awakeDuration = 0
            lightDuration = 0
            remDuration = 0
            deepDuration = 0

            // 至少需要两条数据才能计算时长
            if (tempData.size > 1) {
                // 遍历到倒数第二条数据（最后一条数据只作为结束时间标识）
                for (i in 0 until tempData.size - 1) {
                    val currentItem = tempData[i]
                    val nextItem = tempData[i + 1]

                    // 计算当前睡眠状态的时长（分钟）
                    val durationInMinutes =
                        ((nextItem.createdTime - currentItem.createdTime) / (1000 * 60)).toInt()

                    // 创建SleepChartValueData并设置属性
                    val sleepChartData = SleepChartValueData(
                        timeLong = durationInMinutes,
                        status = currentItem.sleepQuality
                    )

                    listTemp.add(sleepChartData)

                    if(currentItem.sleepQuality >= 1){
                        totalDuration += durationInMinutes
                    }

                    when (currentItem.sleepQuality) {// 睡眠质量 0,清醒(离床) 1:快速眼动 2:浅睡 3:深睡 4:卧床 5:未佩戴 101:小睡（自用） -999：未知（自用）
                        0 -> awakeDuration += durationInMinutes  // 清醒
                        1 -> remDuration += durationInMinutes    // 快速眼动
                        2 -> lightDuration += durationInMinutes  // 浅睡
                        3 -> deepDuration += durationInMinutes   // 深睡
                    }
                }
            }

            // 这里可以使用计算出的各种时长和listTemp进行后续处理
            LogUtils.d("SleepFragment", "睡眠总时长: $totalDuration 分钟")
            LogUtils.d("SleepFragment", "清醒时长: $awakeDuration 分钟")
            LogUtils.d("SleepFragment", "浅睡时长: $lightDuration 分钟")
            LogUtils.d("SleepFragment", "快速眼动时长: $remDuration 分钟")
            LogUtils.d("SleepFragment", "深睡时长: $deepDuration 分钟")
            LogUtils.d("SleepFragment", "SleepChartValueData数组: ${JsonUtils.toJson(listTemp)}")

            mViewContentBinding.tvSleepTime.text = TimeUtils.formatTime2((totalDuration*60000).toLong())
        }

        mViewModel.curHrData.observe(this) { sleepDataIt ->
            val listTemp: MutableList<Int> = ArrayList()
            val tempData: List<UserHeartRate> = sleepDataIt.sortedBy { it.createdTime }//按时间排序（升序）
            LogUtils.d("SleepFragment", "YQ: allSleepData ${JsonUtils.toJson(tempData)}")

            tempData.forEach {userHeartRateIt->
                listTemp.add(userHeartRateIt.heartRate)
            }
            mViewContentBinding.tvSignsTime.text = "${listTemp.average().toInt()}${getString(R.string.common_times_per_minute_splice)}"
        }
    }

    override fun lazyInitData() {
        super.lazyInitData()

        mViewModel.getTheDayData()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.totalSleepBg->toDetails(getString(R.string.common_sleep_hint))
            mViewContentBinding.totalAcBg->toDetails(getString(R.string.common_activity_hint))
            mViewContentBinding.totalPressureBg->toDetails(getString(R.string.common_pressure_hint))
            mViewContentBinding.totalSignsBg->toDetails(getString(R.string.common_signs_hint2))
        }
    }

    private fun finishPdView() {
        mViewContentBinding.pdView.finishRefresh()
        mViewContentBinding.pdView.finishLoadMore()
        mViewContentBinding.pdView.setNoMoreData(true)
    }

    fun toDetails(title:String){
        RouterHelper.navigationPostcard(RouterHub.ROUTER_OVERVIEW_HIS_DATA_DETAILS)
            .withString(KeyBundle.BUNDLE_TITLE, title)
            .navigation()
    }
}